﻿using LeisureNcre.Model;
using System;
using System.ComponentModel;
using System.Configuration;
using System.Diagnostics;
using System.Net;
using System.Threading;
using System.Windows.Forms;

namespace LeisureNcre.Helper
{
    public class UpdateHelper
    {

        //原应用程序路径
        private string _appDirPath;
        //原应用程序文件名
        private string _appFileName;
        //原程序版本号
        private int _oldversioncode;

        //检测版本信息
        VersionInfo info = new VersionInfo();

        //下载文件名
        private string _downfilename = "upgrade.zip";
        //检测升级地址
        private string _checkurl = "";

        private WebClient _client;

        private ProgressBar _progressBar;

        private Label _lbltext;

        public UpdateHelper(string serverIp, int serverPort, ProgressBar pb, Label lbl)
        {
            _progressBar = pb;
            _lbltext = lbl;
            _checkurl = $"http://{serverIp}:{serverPort}/apk/upgradestd.txt";
        }

        /// <summary>
        /// 设置基本参数
        /// </summary>
        /// <param name="apppath"></param>
        /// <param name="appfile"></param>
        /// <param name="oldversioncode"></param>
        public void SetBaseParam(string apppath, string appfile, int oldversioncode)
        {
            _appFileName = appfile;
            _appDirPath = apppath;
            _oldversioncode = oldversioncode;
        }

        /// <summary>
        /// 下载升级文件
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public void DownLoadUpGrade(string url)
        {
            _client = new WebClient();
            if (_client.IsBusy)
            {
                _client.CancelAsync();
            }
            _client.DownloadProgressChanged +=
                new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged);
            _client.DownloadFileCompleted += new AsyncCompletedEventHandler(webClient_DownloadFileCompleted);

            //开始下载
            _client.DownloadFileAsync(new Uri(url), _downfilename);
        }

        /// <summary>
        /// 下载进度条
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void webClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            _progressBar.Value = e.ProgressPercentage;
            _lbltext.Text = $"正在下载文件,完成进度{e.BytesReceived}/{e.TotalBytesToReceive}";
        }


        private void webClient_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                _lbltext.Text = "下载被取消!";
            }
            else
            {
                _lbltext.Text = "下载完成!";
                try
                {
                    StartOver(_downfilename, _appDirPath, info.VersionCode, _appFileName);
                }
                catch (Exception ex)
                {
                    _lbltext.Text = ex.Message;
                }
            }
        }

        /// <summary>
        /// 检测升级信息
        /// </summary>
        /// <param name="geturl"></param>
        /// <param name="downurl"></param>
        /// <returns></returns>
        public void GetUpdaterInfo()
        {
            info = new VersionInfo();

            _client = new WebClient();
            string json = _client.DownloadString(_checkurl);
            info = SerializationHelper.Deserialize<VersionInfo>(json, 0);

            if (info.VersionCode.Equals(_oldversioncode))
            {
                DownLoadUpGrade(info.AppDownloadUrl);
            }
            else
            {
                _lbltext.Text = "当前为最新版本,无需升级!";
                //等待500毫秒后直接启动原程序
                Thread.Sleep(500);
                StartApp(_appFileName);
            }


        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="zipfile"></param>
        /// <param name="destpath"></param>
        public static void StartOver(string zipfile, string destpath, string versioncode, string appfile)
        {
            //解压文件到指定目录
            ZipHelper.UnZipFile(zipfile, destpath, true);
            //成功后修改本地版本信息
            UpdateVersion(versioncode);
            //重新启动源程序 
            if (appfile != "")
            {
                StartApp(appfile);
            }
        }

        /// <summary>
        /// 启动新程序
        /// </summary>
        /// <param name="filename"></param>
        public static void StartApp(string filename)
        {
            ProcessStartInfo info = new ProcessStartInfo();

            info.FileName = filename;
            info.Arguments = "";
            info.WindowStyle = ProcessWindowStyle.Minimized;
            Process pro = Process.Start(info);
            System.Diagnostics.Process.GetCurrentProcess().Kill();
        }

        /// <summary>
        /// 修改更新完后的版本号信息
        ///  </summary>
        /// <param name="newVersionCode"></param>
        private static void UpdateVersion(string newVersionCode)
        {
            //获取Configuration对象
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            //修改版本号
            config.AppSettings.Settings["Version"].Value = newVersionCode.ToString();
            //一定要记得保存，写不带参数的config.Save()也可以
            config.Save(ConfigurationSaveMode.Modified);
            //刷新，否则程序读取的还是之前的值（可能已装入内存）
            ConfigurationManager.RefreshSection("appSettings");
        }
    }
}
